<?php
namespace app\task\controller;
use app\common\library\mstching\PrintHelper;
use app\task\model\PrinterLog as PrinterLogModel;
/**
 * 对对机异步通讯接口
 */

class Mstching
{
    /**
     * 异步通知处理
     */
    public function callback()
    {
        $msg = file_get_contents ('php://input' );
		parse_str($msg,$data); //get字符串转换成数组$data
		if(isset($data['uuid']) OR isset($data['state'])){
			//设备状态通知
			return true;
		}else{
			//打印任务结果通知
			$model = PrinterLogModel::getTaskid($data['taskid']);
			if($data['result']==1){
				//打印成功 - 删除本地打印任务记录
				$model->delete();
				return true;
			}
			//打印失败 - 重新提交
			if($model['n']<5){
				$helper = new PrintHelper();
				//$task_id  打印成功返回任务编号 否则返回 false
				$task_id = $helper->printContent($model['uuid'],$model['content'],$model['open_user_id']);
				for($i=0;$i<5;$i++){
					$task_id = $helper->printContent($model['uuid'],$model['content'],$model['open_user_id']);
					if($task_id){
						break;
					}
				}
				if(!$task_id){
					$task_id = '任务提交失败';
				}
				$model->failreason = $this->p_err($data['failreason']);
				$model->n = ['inc', 1];
			}else{
				$task_id = '任务提交失败';
			}
			//记录$task_id
			$model->task_id = $task_id;
			$model->save();	
			return true;
		}
    }
	
	/**
	 * 错误代码
	 */
	private function p_err($err_code)
	{
		$data = [
			0 => '--',
			1 => '缺纸',
			2 => '温度报警',
			3 => '设备忙',
			4 => '拒绝打印',
			5 => 'uuid不匹配',
			6 => '设备异常',
			7 => '内容解析错误'
		];
		if($err_code<sizeof($data)){
			return $data[$err_code];
		}
		return '未知错误';
	}
	
}
